import { resolveAssetImage } from "@/utils/common"
import AssetKey from "custom/asset_key"
import { useAtomValue } from "jotai"
import { atomFamily, atomWithDefault } from "jotai/utils"
import styled from "@emotion/styled"
const ImageStyled = styled.img``

type ImageProps = ExtractStyledProps<typeof ImageStyled>

type Props = Omit<ImageProps, "src"> & {
    src: AssetKey
}

const imageAtomFamily = atomFamily((src: string) => {
    return atomWithDefault(() => {
        return resolveAssetImage(src as AssetKey)
    })
})

export default function Image(props: Props) {
    const { src: assets_src, ...rest } = props
    const srcPath = useAtomValue(imageAtomFamily(assets_src))
    return (
        <ImageStyled
            src={srcPath}
            {...rest}
        />
    )
}

export function ImageComponent(src: AssetKey) {
    return function Component(props: Omit<Props, "src">) {
        return (
            <Image
                src={src}
                {...props}
            />
        )
    }
}
